package com.guaju.yueshangLife.activity;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.TextureView;
import android.view.View;
import android.widget.AbsoluteLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.githang.statusbar.StatusBarCompat;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.guaju.yueshangLife.R;
import com.guaju.yueshangLife.adapter.CardItem;
import com.guaju.yueshangLife.adapter.CardPagerAdapter;
import com.guaju.yueshangLife.base.BaseFragmentActivity;
import com.guaju.yueshangLife.base.GoodsDetail;
import com.guaju.yueshangLife.bean.AddCartResultBean;
import com.guaju.yueshangLife.bean.LoginInfoBean;
import com.guaju.yueshangLife.databinding.ActivityBuyBinding;
import com.guaju.yueshangLife.fragment.goods.GoodsDetailFragment;
import com.guaju.yueshangLife.global.BaseApplication;
import com.guaju.yueshangLife.net.ApiEntity;
import com.guaju.yueshangLife.net.NetworkUtil;
import com.guaju.yueshangLife.transformer.LoopTransformer;
import com.guaju.yueshangLife.utils.PreferenceUtil;
import com.guaju.yueshangLife.utils.ToastUtil;
import com.guaju.yueshangLife.utils.Utils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class BuyActivity extends BaseFragmentActivity {
    ActivityBuyBinding binding;
    private CardPagerAdapter mCardAdapter;
    private static String selectedSize = "";
    private static String selectedColor = "";
    private static int selectedColorPosition = 0;
    private static int selectedSizePosition = 0;
    GoodsDetail.DataBean.SkuBean selectedSku = null;

    public View news_loading;
    private boolean mShowingFragments = false;
    private JSONObject colorObject;
    private JSONObject sizeObject;
    private List<String> colorArray = new ArrayList<>();
    private List<String> coloNameArray = new ArrayList<>();
    private List<String> sizeArray = new ArrayList<>();
    private List<String> sizeNameArray = new ArrayList<>();
    Gson gson = new Gson();
    private int id;
    private String stock;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_buy);
        EventBus.getDefault().register(this);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.home_background));
        initView();
        addProgressPic();


    }

    @Override
    protected void onResume() {
        super.onResume();
        if (NetworkUtil.isConnected(BuyActivity.this)) {

            try {
                initData();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            binding.viewpager.setPageTransformer(false, new LoopTransformer());
        } else {
            showNetError();
        }
    }

    private void initView() {

        binding.viewpager.setPageMargin(dpToPixels(30, BuyActivity.this));
        binding.etSelectedStock.setText("1");
//       设置不可编辑
        setStockEditable(false);
        setListener();
        goneAllSize();
        goneAllColor();
    }

    private void setListener() {
        binding.etSelectedStock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectedSku == null) {
                    Toast.makeText(BuyActivity.this, "请先选择您喜欢的尺寸和颜色", Toast.LENGTH_SHORT).show();
                } else {
                    setStockEditable(true);
                }
            }
        });

        binding.btAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                先得到库存
                if (selectedSku != null) {
                    int stock = selectedSku.getStock();
                    if (stock <= 0) {
                        ToastUtil.show("暂无库存");
                    }

                    String s = binding.etSelectedStock.getText().toString();
                    int selectedStock = Integer.parseInt(s);
                    if (selectedStock >= stock) {
                        Toast.makeText(BuyActivity.this, "已选择最大数量", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        binding.etSelectedStock.setText(selectedStock + 1 + "");
                    }
                } else {
                    if ((!TextUtils.isEmpty(selectedColor)) && (!TextUtils.isEmpty(selectedSize))) {
                        ToastUtil.show("暂无库存");
                    } else {
                        Toast.makeText(BuyActivity.this, "请选择您喜欢的尺寸和颜色", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        binding.btSubtract.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = binding.etSelectedStock.getText().toString();
                int selectedStock = Integer.parseInt(s);
                if (selectedStock <= 1) {

                } else {
                    binding.etSelectedStock.setText(selectedStock - 1 + "");
                }


            }
        });

        binding.etSelectedStock.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (selectedSku == null) {
                    return;
                }
                String s1 = s.toString();
                if (TextUtils.isEmpty(s1)) {
                    return;
                }
                int i = Integer.parseInt(s1);
                if (i > selectedSku.getStock()) {
                    binding.etSelectedStock.setText(selectedSku.getStock() + "");
                } else if (i < 1) {
                    binding.etSelectedStock.setText("1");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        binding.addToCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (PreferenceUtil.getIsLogin()) {
                    stock = binding.etSelectedStock.getText().toString().trim();
                    int selectStock = Integer.parseInt(stock);
                    if (0 == selectStock) {
                        if (TextUtils.equals("库存0件", binding.tvStock.getText().toString().trim())) {
                            ToastUtil.show("抱歉，该规格服装暂无库存");
                        } else {
                            Toast.makeText(BuyActivity.this, "请选择您需要的商品数量", Toast.LENGTH_SHORT).show();
                        }
                    } else {
//                    要购买的sku_id
                        if (selectedSku != null) {
                            int sku_id = selectedSku.getSku_id();
                            ApiEntity.addToCart(id, sku_id, stock);
                        }

                    }
                } else {
                    Toast.makeText(BuyActivity.this, "请先登录~", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(v.getContext(), LoginActivity.class);
                    startActivity(intent);
                }
            }
        });
    }

    private void initData() throws JSONException {

        Intent intent = getIntent();
        GoodsDetail.DataBean goodsDetailData = BaseApplication.getInstance().getCurrentGoodsDetail();
        id = goodsDetailData.getId();
//        价格
        showPrice(goodsDetailData);
//        图片
        showBuyViewPager(goodsDetailData);
//        请求String类型数据
        ApiEntity.goodsDetailString(goodsDetailData.getId() + "");
        final List<GoodsDetail.DataBean.SkuBean> sku = goodsDetailData.getSku();
//        根据选择的尺寸和颜色变换价格（图片后期变化）
        binding.colorRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
//                现将数量设置为0
                binding.etSelectedStock.setText("0");


                for (int i = 0; i < colorArray.size(); i++) {
                    RadioButton childAt = (RadioButton) group.getChildAt(i);
                    if (checkedId != 0 && childAt.isChecked()) {
                        selectedColorPosition = i;
                        selectedColor = colorArray.get(i);
                        binding.tvColorTip.setTextColor(Color.parseColor("#666666"));
                        binding.tvColorTip.setText("已选择\"" + coloNameArray.get(i) + "\"");
                    }
                }


                if ((!TextUtils.isEmpty(selectedColor)) && (!TextUtils.isEmpty(selectedSize))) {
                    //若两项选中
                    for (int i = 0; i < sku.size(); i++) {
                        String s1 = sku.get(i).getAttributes().get(0) + "";
                        String s2 = sku.get(i).getAttributes().get(1) + "";
                        if (selectedColor.equals(s1) && selectedSize.equals(s2)) {
                            //找到选中的
                            selectedSku = sku.get(i);
                            break;
                        }
                    }

                    if (selectedSku != null) {
//                        设置价格
                        binding.price.setText("¥" + selectedSku.getPrice().getCurrent());
//                        设置库存
                        binding.tvStock.setText("库存" + selectedSku.getStock() + "件");
                    } else {
//                        设置库存
                        binding.tvStock.setText("库存0件");
                    }
//                    设置可编辑
//                    setStockEditable(true);
                }
            }

        });

        binding.sizeRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                binding.etSelectedStock.setText("0");
                for (int i = 0; i < sizeArray.size(); i++) {
                    RadioButton childAt = (RadioButton) group.getChildAt(i);
                    if (checkedId != 0 && childAt.isChecked()) {
                        selectedSize = sizeArray.get(i);
                        selectedSizePosition = i;
                        binding.tvSizeTip.setTextColor(Color.parseColor("#666666"));
                        binding.tvSizeTip.setText("已选择\"" + sizeNameArray.get(i) + "\"");
                    }
                }
                if ((!TextUtils.isEmpty(selectedColor)) && (!TextUtils.isEmpty(selectedSize))) {
                    //若两项选中
                    for (int i = 0; i < sku.size(); i++) {
                        String s1 = sku.get(i).getAttributes().get(0) + "";
                        String s2 = sku.get(i).getAttributes().get(1) + "";
                        if (selectedColor.equals(s1) && selectedSize.equals(s2)) {
                            //找到选中的

                            selectedSku = sku.get(i);
                            break;
                        }
                    }

                    if (selectedSku != null) {
//                        设置价格
                        binding.price.setText("¥" + selectedSku.getPrice().getCurrent());
//                        设置库存
                        binding.tvStock.setText("库存" + selectedSku.getStock() + "件");
                    }

                }
            }
        });

        //      设置默认状态
        setDefaultSelectTip();

    }

    private void showPrice(GoodsDetail.DataBean goodsDetailData) {
        String current = goodsDetailData.getPrice().getCurrent();
        binding.price.setText("¥" + current);
    }

    private void showBuyViewPager(GoodsDetail.DataBean goodsDetailData) {
        List<GoodsDetail.DataBean.ImagesBean> images = goodsDetailData.getImages();
        mCardAdapter = new CardPagerAdapter();
        for (GoodsDetail.DataBean.ImagesBean imagesBean : images) {
            mCardAdapter.addCardItem(new CardItem(imagesBean.getHost() + imagesBean.getPath()));
        }
        binding.viewpager.setAdapter(mCardAdapter);
    }

    private void setStockEditable(boolean value) {
        binding.etSelectedStock.setFocusableInTouchMode(value);
        binding.etSelectedStock.setFocusable(value);
        if (value) {
            binding.etSelectedStock.requestFocus();
        }
    }

    private void goneAllSize() {
        int childCount = binding.sizeRadioGroup.getChildCount();
        for (int i = 0; i < childCount; i++) {
            binding.sizeRadioGroup.getChildAt(i).setVisibility(View.GONE);
        }
    }

    private void goneAllColor() {
        int childCount = binding.colorRadioGroup.getChildCount();
        for (int i = 0; i < childCount; i++) {
            binding.colorRadioGroup.getChildAt(i).setVisibility(View.GONE);
        }
    }

    public static int dpToPixels(int dp, Context context) {
        return (int) (dp * (context.getResources().getDisplayMetrics().density));
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGoodsDetailString(String str) {
        if (!TextUtils.isEmpty(str)) {
            try {
                JSONObject jsonObject = new JSONObject(str);
                JSONObject data = jsonObject.getJSONObject("data");
                if (data == null) {
//                    添加购物车
                    Toast.makeText(this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                    return;
                }

                JSONArray attributes = data.getJSONArray("attributes");
                JSONObject colorO = (JSONObject) attributes.get(0);
                JSONObject colorObject = colorO.getJSONObject("values");
                JSONObject sizeO = (JSONObject) attributes.get(1);
                JSONObject sizeObject = sizeO.getJSONObject("values");
                /**
                 * 颜色
                 */
                JSONObject price = data.getJSONObject("price");
                String current = price.getString("current");
                String original = price.getString("original");
                String wholesale = price.getString("wholesale");
                binding.price.setText("¥" + current);
//        颜色
                goneAllColor();
//                colorArray = new ArrayList<>();
//                coloNameArray = new ArrayList<>();
                Iterator<String> colorkeys = colorObject.keys();
                for (int i = 0; i < colorObject.length(); i++) {
                    RadioButton radioButton = (RadioButton) binding.colorRadioGroup.getChildAt(i);
                    radioButton.setVisibility(View.VISIBLE);
                    String next = colorkeys.next();
                    colorArray.add(next);
                    coloNameArray.add(colorObject.getString(next));
                    radioButton.setText(colorObject.getString(next));
                }
//        尺寸
                goneAllSize();
                Iterator<String> sizekeys = sizeObject.keys();

                for (int i = 0; i < sizeObject.length(); i++) {
                    RadioButton radioButton = (RadioButton) binding.sizeRadioGroup.getChildAt(i);
                    radioButton.setVisibility(View.VISIBLE);
                    String next = sizekeys.next();
                    sizeArray.add(next);
                    sizeNameArray.add(sizeObject.getString(next));
                    radioButton.setText(sizeObject.getString(next));
                }

                if (news_loading != null) {
                    news_loading.setVisibility(View.GONE);
                }


            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void setDefaultSelectTip() {
        binding.tvColorTip.setText(R.string.color_tip);
        binding.tvSizeTip.setText(R.string.size_tip);
        binding.tvSizeTip.setTextColor(Color.parseColor("#FE3824"));
        binding.tvColorTip.setTextColor(Color.parseColor("#FE3824"));
//        #666666
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(AddCartResultBean bean) {
        if (bean == null) return;
        int code = bean.getCode();
        String msg = bean.getMsg();
        if (200 == code) {
            ToastUtil.show(msg);
            Intent intent = new Intent();
            intent.putExtra("code", 200);
            intent.putExtra("num", stock);
            setResult(GoodsDetailActivity.RESULTCODE, intent);
            finish();
        }
    }

    public void addProgressPic() {
        news_loading = View.inflate(BuyActivity.this, R.layout.loading, null);
        news_loading.setLayoutParams(new AbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.MATCH_PARENT, AbsoluteLayout.LayoutParams.MATCH_PARENT, 0, 0));
        Bitmap mBgBitmap = Utils.readBitMap(BuyActivity.this, R.drawable.buy_loading);
        news_loading.setBackgroundDrawable(new BitmapDrawable(mBgBitmap));
        binding.rlContainer.addView(news_loading);
        news_loading.setVisibility(View.VISIBLE);
    }

}
